<?php

class PagamentoService extends Model {

    /**
     * @var PagamentoDao
     */
    private $pagamentoDao;
    /**
     * @var UsuarioService
     */
    private $usuarioService;

    public function injectDependencies() {
        $this->pagamentoDao = PagamentoDao::getInstance();
        $this->usuarioService = UsuarioService::getInstance();
    }

    public function release($IDUsuario, $ArPayments) {
        $Usuario = $this->usuarioService->findById($IDUsuario);
        if( ! $this->pagamentoDao->releasePayment($Usuario->getArDadosAdministracao('IDAdministracao'), $ArPayments) ) {
            return false;
        }
        if( $Usuario->getIDUsuario() == Dracosys::getLoggedUser()->getIDUsuario() ) {
            $this->usuarioService->reload();
        }
        return true;
    }

    public function findPendingPeriodByUser($Usuario) {
        $ArPeriodsOfPayments = $this->generatePeriodsOfPaymentByUser($Usuario);
        $ArPendingPeriods = array();
        foreach( $ArPeriodsOfPayments as $Period ) {
            if( !$Usuario->hasThisPeriodPayment($Period) ) {
                $ArPendingPeriods[] = $Period;
            }
        }
        return $ArPendingPeriods;
    }

    public function findPaymentFromLoggedUserById($IDPagamento) {
        foreach(Dracosys::getLoggedUser()->getArPagamentos() as $Payment) {
            if( $Payment->getIDPagamento() == $IDPagamento ) {
                return $Payment;
            }
        }
        return false;
    }

    private function generatePeriodsOfPaymentByUser($Usuario) {
        $ArCurrentPeriod =  $this->splitPeriod( now() );
        $ArAdmissionPeriod = $this->splitPeriod( $Usuario->getArDadosAdministracao('DtAdmissao') );
        $ArPeriods = array();
        $month = $ArAdmissionPeriod['MES'];
        for($year = $ArAdmissionPeriod['ANO']; $year <= $ArCurrentPeriod['ANO']; $year++) {
            for($limit = $this->getLimitOfPeriodsForThisYear($year); $month <= $limit ; $month++) {
                $ArPeriods[] = $year . '-' . $month;
            }
            $month = 1;
        }
        return $ArPeriods;
    }

    private function getLimitOfPeriodsForThisYear($year) {
        $ArCurrentPeriod = $this->splitPeriod( now() );
        if( $year != $ArCurrentPeriod['ANO'] ) {
            return 12;
        }
        return $ArCurrentPeriod['MES'];
    }

    private function splitPeriod($DtDate) {
        $ArSplitDate = explode('-', $DtDate);
        return array(
            'MES' => $ArSplitDate[1],
            'ANO' => $ArSplitDate[0]
        );
    }

}

?>
